package com.wyp168.leetcode;

/**
 * @ClassName ReformatNumberSolution
 * @Title TODO leetcode 1694： 重新格式化字符串 【Easy】
 * @Description TODO
 * @Author wyp168
 * @Date 2022/10/20 20:26
 */
public class ReformatNumberSolution {
    public static void main(String[] args) {
        String number = "1-23-45 6";
        ReformatNumberSolution solution = new ReformatNumberSolution();
        System.out.println(solution.reformatNumber(number));
    }

    public String reformatNumber(String number) {
        int length = number.length();
        int index = 0, count = 0;
        StringBuilder result = new StringBuilder();
        while (index < length) {
            char numChar = number.charAt(index);
            if (numChar >= '0' && numChar <= '9') {
                //如果是数字，则拼接到result字符串中
                result.append(numChar);
                count++;
            }
            if (count == 3) {
                count = 0;
                result.append("-");
            }
            index ++;
        }
        int sbs = result.length();
        if (count == 1) {   //存在尾部长度为2的号码
            result.replace(sbs - 2, sbs - 1, String.valueOf(result.charAt(sbs - 3)));
            result.replace(sbs - 3, sbs - 2, "-");
        }
        if (result.charAt(sbs - 1) == '-') {
            result.replace(sbs -1, sbs, "");
        }

        return result.toString();
    }
}
